<template>
  <div class="container">
    <XForm
      ref="xform"
      :fields="fields"
      :value="defaultValue"
      cancel-text="重置"
      ok-text="保存"
      @submit="submit"
    ></XForm>
  </div>
</template>

<script lang="ts" setup>
  import { ref } from 'vue';
  import { updateUserPwd } from '@/api/user-center';
  import { Message } from '@arco-design/web-vue';

  const xform = ref();
  const defaultValue = ref({});
  const fields = ref([
    {
      key: 'oldPassword',
      label: '旧密码',
      placeholder: '请输入旧密码',
      tag: 'a-input-password',
      span: 24,
      decorator: {
        rules: [{ required: true, message: '请输入旧密码' }],
      },
    },
    {
      key: 'newPassword',
      label: '新密码',
      placeholder: '请输入新密码',
      tag: 'a-input-password',
      span: 24,
      decorator: {
        rules: [
          { required: true, message: '请输入新密码' },
          {
            minLength: 6,
            maxLength: 20,
            message: '长度在 6 到 20 个字符',
          },
        ],
      },
    },
    {
      key: 'confirmPassword',
      label: '确认密码',
      placeholder: '请输入确认密码',
      tag: 'a-input-password',
      span: 24,
      decorator: {
        rules: [
          { required: true, message: '请输入确认密码' },
          {
            required: true,
            validator: (value: any, callback: any) => {
              const data = xform.value.getData();
              if (data.newPassword !== value) {
                callback('确认密码与新密码不一致');
              }
            },
          },
        ],
      },
    },
  ]);

  const submit = async (e: any) => {
    const { code, msg } = await updateUserPwd(e);
    if (code !== 200) {
      Message.error(msg);
    }
  };
</script>

<style scoped lang="less">
  .container {
    width: 800px;
    margin: 0 auto;
  }
</style>
